from tools.initialization_config import *
from audio.record import *
import speech_recognition as sr
import datetime


class IBMSpeechRecognizer(object):
    def __init__(self):
        self.cuid = get_mac_address()
        self.username, self.password = self.get_ibm_api_config()

    def get_ibm_api_config(self):
        _CONF_PATH = 'speech/ibm/IBMOAuth.ini'
        ini_parser = InitializationConfigParser(_CONF_PATH)
        client_credentials = ini_parser.GetAllNodeItems("ClientCredentials")
        username = client_credentials.get("username")
        password = client_credentials.get("password")
        return username, password

    def wav_file_recognition(self, filename):
        # 音频分块识别
        r = sr.Recognizer()
        try:
            with sr.WavFile(filename) as source:
                audio = r.record(source)
                text = r.recognize_ibm(audio, username=self.username, password=self.password, language='en-US')
                return text

        except Exception as e:
            print(e)
            temp_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print('%s %s 未完成' % (temp_time, filename))